package com.springcloud.controller;

import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.swing.*;
import java.awt.*;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @Author: wukc
 * @Description: TODO  处理PDF
 * @DateTime: 2022/1/6 14:48
 **/
@RestController
public class HandlePDF {

    private final static Logger logger = LoggerFactory.getLogger("HandlePDF");

    //下载文件路径
    @Value("${fileUpload.info}")
    private String path;

    /**
     * 处理pdf
     * @param uuid  文件标识
     * @param str  需要加的水印
     * @throws Exception
     */
    @RequestMapping(value = "handlePDF")
    public void handlePDF(String uuid,String str) throws Exception {
        // 根据uuid获取文件
        File f = new File(path);
        String filename = "";
        String filepath = "";
        if (!f.exists()) {
            System.out.println(filepath + " not exists");
            return;
        }
        File fa[] = f.listFiles();
        for (int i = 0; i < fa.length; i++) {
            File fs = fa[i];
            if (!fs.isDirectory()) {
                String filename1 = fs.getName();
                if(filename1.indexOf(uuid)!=-1){
                    filename = filename1.replace((uuid+"-"),"");
                    filepath = fs.getPath();
                    break;
                }
            }
        }
        if(filename== ""){
            logger.info("-----------文件不存在或已损坏----------------"+uuid);
            throw new Exception("文件不存在，或已损坏");
        }
        // 要输出的pdf文件
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(filepath)));
        // 将pdf文件先加水印然后输出
         setWatermark(bos, filepath, str);
    }
    /**
     *
     * @param bos
     * @param input
     *            原PDF位置
     * @param waterMarkName
     *            页脚添加水印
     * @throws DocumentException
     * @throws IOException
     */
    public static void setWatermark(BufferedOutputStream bos, String input, String waterMarkName)
            throws DocumentException, IOException {

        PdfReader reader = new PdfReader(input);
        PdfStamper stamper = new PdfStamper(reader, bos);

        // 获取总页数 +1, 下面从1开始遍历

        int total = reader.getNumberOfPages() + 1;
        // 使用classpath下面的字体库
        BaseFont base = null;
        try {
            base = BaseFont.createFont("D:\\program\\Cloud\\cloud-consumer-feign-hystrix-order80\\src\\STSONG.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        } catch (Exception e) {
            // 日志处理
            e.printStackTrace();
        }

        // 间隔
        int interval = 50;
        // 获取水印文字的高度和宽度
        int textH = 0, textW = 0;
        JLabel label = new JLabel();
        label.setText(waterMarkName);
        FontMetrics metrics = label.getFontMetrics(label.getFont());
        textH = metrics.getHeight();
        textW = metrics.stringWidth(label.getText());
        System.out.println("textH: " + textH);
        System.out.println("textW: " + textW);

        // 设置水印透明度
        PdfGState gs = new PdfGState();
        //gs.setFillOpacity(0.3f);
        //gs.setStrokeOpacity(0.3f);

        String tempStr = waterMarkName;
        Rectangle pageSizeWithRotation = null;
        PdfContentByte content = null;
        for (int i = 1; i < total; i++) {
            //第一页不要水印
            if(i>1) {
                /*if (i < 11) {
                    waterMarkName = tempStr + "00" + (i-1);
                } else if (i > 10 && i < 100) {
                    waterMarkName = tempStr + "0" + (i-1);
                } else {
                    waterMarkName = tempStr + (i-1);
                }*/
                // 在内容上方加水印
                content = stamper.getOverContent(i);
                // 在内容下方加水印
                // content = stamper.getUnderContent(i);
                content.saveState();
                content.setGState(gs);

                // 设置字体和字体大小
                content.beginText();
                content.setFontAndSize(base, 26);

                // 获取每一页的高度、宽度
                pageSizeWithRotation = reader.getPageSizeWithRotation(i);
                double pageHeight = pageSizeWithRotation.getHeight();
                double pageWidth = pageSizeWithRotation.getWidth();

                // 根据纸张大小多次添加， 水印文字成45度角倾斜
                /*for (int height = interval + textH; height < pageHeight; height = height + textH * 30) {
                    for (int width = interval + textW; width < pageWidth + textW; width = width + textW * 2) {

                    }
                }*/
                int height = 60;
                int width = 400;
                content.showTextAligned(Element.ALIGN_LEFT, waterMarkName, height - textH, width - textW, -45);

                height = 180;
                width = 650;
                content.showTextAligned(Element.ALIGN_LEFT, waterMarkName, height - textH, width - textW, -45);

                height = 300;
                width = 900;
                content.showTextAligned(Element.ALIGN_LEFT, waterMarkName, height - textH, width - textW, -45);

                content.endText();
            }
        }

        // 关流
        stamper.close();
        reader.close();
    }
}
